import tbPermission from "./permission";

class PerData {
	constructor() {
		this.routeData = [];
		this.btnData = [];
		this.accessedRouters = [];
	}

	setPermissions(permissions, routers) {
		//router与button归类
		permissions.map(per => {
			if (per.type === '1') {
				this.routeData.push(per.frontUrl)
			}
			if (per.type === '2') {
				this.btnData.push(per)
			}
		})
		
		
		this.accessedRouters = this.filterAsyncRouterMenu(routers, this.routeData);
		
		console.log("this.accessedRouters",this.accessedRouters)
		return this.accessedRouters;
	}

	getPermissionComponent() {
		
		return {
			install: (Vue, options = {
				data: this.btnData
			}) => {
				if (typeof window !== "undefined" && window.Vue) {
					Vue = window.Vue;
				}

				//全局注册组件（组件名，组件）
				Vue.component("tb-per", tbPermission(options.data));
			}
		};
	}

	hasRoute(url){
		const index = this.routeData.findIndex(item=>item==url)
		return index !==-1
	}

	hasRouteData() {
		return this.routeData.length==0;
	}
	
	getAccessedRouters() {
		return this.accessedRouters;
	}

	filterAsyncRouterMenu(routerMap, menus) {
		const accessedRouters = routerMap.filter(route => {
			if (this.hasMenus(menus, route)) {
				if (route.children && route.children.length) {
					route.children = this.filterAsyncRouterMenu(route.children, menus)
				}
				return true
			}
			return false
		})
		return accessedRouters
	}

	hasMenus(menus, route) {
		let flag = false
		if (route.path === '/') {
			return true
		}
		for (let i = 0; i < menus.length; i++) {
			flag = route.path === menus[i]
			if (flag) {
				return true
			}
		}
		return false
	}
}

const tempData = new PerData();
export default tempData;
